"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 参数fields terminated by 'string'入参验证,部分测试点合理报错
Create At   : 2023/06/02
Owner       : n@ningyali
Description :
        1.建表
        2.不指定分隔符,默认是tab字符（\t）
        3.指定分隔符,string长度为10个字节
        4.指定分隔符,string长度大于10个字节
        5.指定分隔符为字母
        6.指定分隔符为数字
        7.清理环境
Expect      :
        1.创建成功
        2.成功
        3.成功
        4.合理报错
        5.成功
        6.成功
        7.成功
History     :
"""
import os
import unittest

from yat.test import Node

from testcase.COMPATIBILITY.GRAMMAR.LOAD. \
    Opengauss_Compatibility_Grammar_Load_Common import \
    LoadData
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class LoadData0039(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.common = Common()
        self.load_data = LoadData()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.case_lable = 'load_data_0039'
        self.db_name = f'db_{self.case_lable}'
        self.t_name = f't_{self.case_lable}'
        self.file_path = os.path.join('/home', self.pri_user.ssh_user)
        self.cols = 'c_id int,c_name varchar(50),c_age int,' \
                    'c_gender varchar(11)'

        text1 = '----pre_step1：创建数据文件；expect:创建成功----'
        self.log.info(text1)
        self.data1 = "1	'aaa'	12	test\n2	'bbb'	13	test\n" \
                     "3	'ccc'	12	test\n4	'ddd'	13	test"
        self.data2 = "+1----------amy1----------18----------'男'+" \
                     "+2----------amy2----------17----------'&n'+"
        self.data3 = self.data2.replace('----------', '-----------')
        self.data4 = "[1!*amy1*!18!*男*)" \
                     "[2!*amy2*!17!*女*)" \
                     "[3!*小明*!16!**)"
        self.data5 = r"{{1￥小一￥18￥男……" \
                     r"{{2￥小二￥18￥女……" \
                     r"{{3￥尔尔￥18￥男……"
        res = self.load_data.create_data_file(self.pri_user, self.case_lable,
                                              self.data1, self.data2,
                                              self.data3, self.data4,
                                              self.data5)
        self.assertTrue(res, '执行失败:' + text1)

        text2 = '----pre_step2：创建兼容B库；expect:创建成功----'
        self.log.info(text2)
        res = self.load_data.create_b_db(self.pri_sh, self.db_name)
        self.assertTrue(res, '执行失败:' + text2)

    def test_load(self):
        text = '----step1：建表；expect：建表成功----'
        self.log.info(text)
        res = self.load_data.create_table(self.pri_sh, self.db_name,
                                          self.t_name, self.cols)
        self.assertTrue(res, '执行失败:' + text)

        text = r"----step2：不指定分隔符,默认是tab字符（\t）；expect：成功----"
        self.log.info(text)
        f_path1 = os.path.join(self.file_path, f'{self.case_lable}_1.txt')
        sql1 = f"load data infile '{f_path1}' into " \
            f"table {self.t_name} fields enclosed by '''';" \
            f"select * from {self.t_name};"
        res1 = self.pri_sh.execut_db_sql(sql1, dbname=self.db_name)
        self.log.info(res1)
        rows, _ = self.common.parse_sql_query_res(res1)
        expect = [['1', 'aaa', '12', 'test'], ['2', 'bbb', '13', 'test'],
                  ['3', 'ccc', '12', 'test'], ['4', 'ddd', '13', 'test']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = "----step3：指定分隔符,string长度为10个字节；expect：成功----"
        self.log.info(text)
        f_path2 = os.path.join(self.file_path, f'{self.case_lable}_2.txt')
        res2 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path2,
                                        into_type='', col_sep='----------',
                                        line_start='+', line_end='+')
        rows, _ = self.common.parse_sql_query_res(res2)
        expect = [['1', 'amy1', '18', '男'], ['2', 'amy2', '17', '&n']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = "----step4：指定分隔符,string长度大于10个字节；expect：合理报错----"
        self.log.info(text)
        f_path3 = os.path.join(self.file_path, f'{self.case_lable}_3.txt')
        res3 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path3,
                                        into_type='', col_sep='-----------',
                                        line_start='+', line_end='+')
        einfo = 'ERROR:  COPY delimiter must be less than 10 bytes'
        self.assertIn(einfo, res3, '执行失败' + text)

        text = "----step5：指定分隔符为英文特殊符号；expect：成功----"
        self.log.info(text)
        f_path4 = os.path.join(self.file_path, f'{self.case_lable}_4.txt')
        res4 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path4,
                                        into_type='', col_sep='!',
                                        col_end='*',
                                        line_start='[', line_end=')')
        rows, _ = self.common.parse_sql_query_res(res4)
        expect = [['1', 'amy1', '18', '男'], ['2', 'amy2', '17', '女'],
                  ['3', '小明', '16', '']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = "----step6：指定分隔符为中文特殊符号；expect：成功----"
        self.log.info(text)
        f_path5 = os.path.join(self.file_path, f'{self.case_lable}_5.txt')
        res5 = self.load_data.load_data(self.pri_sh, self.db_name,
                                        self.t_name, f_path5,
                                        into_type='', col_sep='￥',
                                        line_start='{{', line_end='……')
        rows, _ = self.common.parse_sql_query_res(res5)
        expect = [['1', '小一', '18', '男'], ['2', '小二', '18', '女'],
                  ['3', '尔尔', '18', '男']]
        self.assertEqual(rows, expect, '执行失败' + text)

    def tearDown(self):
        self.log.info('----清理环境----')
        res = self.load_data.clear_env(self.pri_sh, self.pri_user,
                                       self.db_name,
                                       os.path.join(self.file_path,
                                                    f"{self.case_lable}*"))
        self.assertTrue(res, '执行失败:清理环境')
        self.log.info(f'----{os.path.basename(__file__)} end----')
